package com.example.auth.utils;

import com.example.auth.constants.CommonConstants;
import com.example.auth.model.SysClient;
import com.example.auth.model.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * Created by wangtao on 2018/3/2.
 */
public class JwtUtil {
    private Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    @Value("${jwt.user.expire}")
    private int userExpire;
    @Value("${jwt.user.priKey.path}")
    private String userPriKeyPath;
    @Value("${jwt.client.expire}")
    private int clientExpire;
    @Value("${jwt.client.priKey.path}")
    private String clientPriKeyPath;

    public String generateTokenByUser(User user) throws Exception {
        String token =  Jwts.builder()
                .setSubject(user.getUserLoginName())
                .claim(CommonConstants.JWT_KEY_USER_ID,user.getId())
                .claim(CommonConstants.JWT_KEY_USER_NAME,user.getUsername())
                .setExpiration(DateTime.now().plusSeconds(userExpire).toDate())
                .signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(userPriKeyPath))
                .compact();
        return token;
    }

    public String generateTokenByClient(SysClient client) throws Exception {
        String token =  Jwts.builder()
                .setSubject(client.getCode())
                .claim(CommonConstants.JWT_KEY_CLIENT_ID,client.getId())
                .claim(CommonConstants.JWT_KEY_CLIENT_SECRET,client.getSecret())
                .setExpiration(DateTime.now().plusSeconds(clientExpire).toDate())
                .signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(clientPriKeyPath))
                .compact();
        return token;
    }

    public int getExpired(){
        return userExpire;
    }
}
